package com.zx.club.oss.config;

import com.zx.club.oss.adapter.MinioStorageServiceAdapter;
import com.zx.club.oss.adapter.StorageServiceAdapter;
import com.zx.club.oss.util.MinioUtil;
import io.minio.MinioClient;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * minio配置类
 *
 * @author zx
 * @date 2025-03-04 20:08
 */
@ConditionalOnProperty(prefix = "oss", name = "type", havingValue = "minio")
@Configuration
public class MinioConfig {
    @Resource
    private OssProperties ossProperties;

    @Bean
    public MinioClient minioClient() {
        MinioProperties minioProperties = ossProperties.getMinio();
        try {
            return MinioClient.builder()
                    .endpoint(minioProperties.getUrl())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();
        } catch (Exception e) {
            throw new RuntimeException("Error initializing MinIO client", e);
        }
    }

    @Bean
    @ConditionalOnBean(MinioClient.class)
    public MinioUtil minioUtil(MinioClient minioClient) {
        return new MinioUtil(minioClient);
    }

    @Bean("minioStorageService")
    @ConditionalOnBean(MinioUtil.class)
    public StorageServiceAdapter StorageServiceAdapter(MinioUtil minioUtil){
        return new MinioStorageServiceAdapter(ossProperties,minioUtil);
    }

}
